define([
	'jquery',
	'services/md5'
], function($, Hash){
	var baseURL = "http://a.wykop.pl/";
	var apiParams = "appkey/mpUtnPXzkW/";//format/jsonp/";
	var privateKey = "zGP3gJ0AlP";

	/*
	 * http://a.wykop.pl/Stream/Index/appkey/mpUtnPXzkW/page/1/format/jsonp
	 * 
	 params {
	 	method: [Stream, Index]
	 	methodParams: [1, 1, 3]
	 	api: [userkey, fhakkaljs, page, 67]
	 	post: {
	 		body: 'ala ma kota kurwa jego pierdolona zajebana mac',
	 		embed: 'http://c3201142.cdn03.imgwykop.pl/comment_XfrEC8NftgpYJkdUyhlRxOH84cjltKg8.jpg'
	 	}
	 	success: function(data) {...}
	 	error: function(data) {...}
	 }
	 */
	var send = function(p) {
		var encodedURL = encodeURL(p);
		var signum = sign(encodedURL, p.post);
		
		$.ajax({
			url: encodedURL,
			type: (p.post && p.post.length > 0 ? "POST" : "GET"),
			headers: {"apisign" : signum},
			async: false, //pozniej zmienic
			data: p.post,
			success: function(data) {
				console.log('success');
				console.log(data);
				p.success(data);
			},
			error: function(data) {
				console.log('error');
				console.log(data);
				p.error(data);
			}
		});
	};
	
	function encodeURL(p) {
		var encodedURL = baseURL;
		if(p.method && p.method.length > 0) {
			encodedURL = encodedURL.concat(p.method.join('/') + '/');
		}
		if(p.methodParams && p.methodParams.length > 0) {
			encodedURL = encodedURL.concat(p.methodParams.join('/') + '/');
		}
		if(p.api && p.api.length > 0) {
			encodedURL = encodedURL.concat(p.api.join('/') + '/');
		}
		return encodedURL + apiParams;
	};
	
	function sign(url, post) {
		if(post) {
			post = $.param(post);
			var postCouples = post.split("&");
			var values = [];
			
			postCouples.sort();
			
			$.each(postCouples, function(index, couple){
				values.push(couple.split("=")[1]);
			});
			
			post = values.join().split("+").join(" ");
		}
		
		return Hash.md5(privateKey + url + post);
	};
	
	return {
		send: send
	};
});